package qplayas.crawling.builder

import com.gargoylesoftware.htmlunit.BrowserVersion
import com.gargoylesoftware.htmlunit.WebClient
import com.gargoylesoftware.htmlunit.html.*

class HtmlUnitBuilder{
    
    WebClient client
    HtmlPage currentPage
    HtmlForm currentForm
    HtmlInput currentSubmit
    
    def client(browserVersion,Closure closure){
        this.client = new WebClient(browserVersion ? browserVersion : BrowserVersion.FIREFOX_3_6)
        this.client.setJavaScriptEnabled(false)
        this.client.setCssEnabled(false)
        with(closure)  
    }
    
    def page(Map map,Closure closure){
		try{
			currentPage = client.getPage(map.url)       
			with(closure)
		} catch (ex){
			println "Error getting page: ${ex.message}"
		}
    }
    
    def page(Closure closure){
		try{
			currentPage = currentSubmit.click()		
			with(closure)
		} catch (ex){
			println "Error submitting form: ${ex.message}"
		}
    }
    
    def methodMissing(String name, argsArray) {
        def closure = argsArray[0]
        def attributesMap = [:]
        
        try{
         /* If there're fields to set */
              attributesMap.with(closure)
          /* Setting the html input fields */    
            attributesMap.entrySet().each{entry->
                def field
                try{
                    field = currentForm.getInputByName(entry.key)
                    field.valueAttribute = entry.value
                } catch (ex){
                    println "isn't an input"
                }
                try{
                    if (!field){
                        field = currentForm.getSelectByName(entry.key)
                        field.setSelectedAttribute(entry.value,true)                    
                    }    
                } catch (ex){
                    println "isn't a select"
                }
            }
        } catch (ex){
          println "There werent fields to set"
        }
       
    }
    
    def anchors(){
        return currentPage.getAnchors()
    }
    
    def elementsByXPath(String expression){
        return currentPage.getByXPath(expression)
    }
    
    def form(String form,String submit,Closure closure){                    
        try{
            def cp = currentPage
            def forms = []
            def moreThanOneForm = currentPage.getByXPath("//form[@name='$form']")
            def justOneForm = currentPage.getFormByName(form)
            
            if (!moreThanOneForm && moreThanOneForm.size == 1){
                println "just one form"
                forms << justOneForm
            } else {
                println "There're ${moreThanOneForm.size}"
                forms.addAll(moreThanOneForm)
            }
            println "Looping through ${forms.size} forms"
            forms.each{cf->
                
                currentSubmit = cf.getElementsByAttribute("input","class",submit)[0]
                currentSubmit = currentSubmit ? currentSubmit : cf.getFirstByXPath("/child::*/input[@name='$submit']") 
                currentSubmit = currentSubmit ? currentSubmit : cf.getElementsByAttribute('input','type','submit')[0]
                
                currentForm = cf
                
                with(closure)
                
                currentPage = cp
            }
        } catch (ex){
            println "No hay formulario con nombre $form $ex.message"
        }        
    }
	
	def normalizeName(name) {
        def parts = name.toLowerCase().split(/\s/)
        def fName = ""
        parts.each{p->
            fName += 
				p.
				replaceAll('á','a').
				replaceAll('é','e').
				replaceAll('í','i').
				replaceAll('ó','o').
				replaceAll('ú','u').
				replaceAll('ñ','n').
				replaceAll("'","").
				replaceAll("/","").
			capitalize()
        }
        fName = "${fName.substring(0,1).toLowerCase()}${fName.substring(1)}"
        return fName
    }
}